#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>

void setNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("fcntl error:");
        return;
    }
    fl = fcntl(fd, F_SETFL, fl | O_NONBLOCK);
    if (fl < 0)
    {
        perror("fcntl error:");
        return;
    }
}

int main()
{
    char buf[32] = {0};
    // 非阻塞从0号文件描述符读取数据
    setNonBlock(0);
    while (true)
    {
        std::cout << "enter# ";
        fflush(stdout);
        ssize_t n = read(0, buf, sizeof(buf) - 1);
        if (n > 0)
        {
            buf[n - 1] = 0;
            std::cout << buf << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "end of file" << std::endl;
        }
        else
        {
            // 非阻塞，IO事件未就绪，以出错的方式提醒用户
            // read读事件未就绪，errno=11->EAGAIN || EWOULDBLOCK

            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "data not ready" << std::endl;
                sleep(1);
                continue;
            }
            else
            {
                std::cout << "read error, errno: " << errno << ", strerror: " << strerror(errno) << std::endl;         
                break;      
            }
        }
    }

    return 0;
}